{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Title: #Rank Teams by Votes"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Difficulty: #Medium"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Category Title: #Algorithms"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Tag Slug: #array #hash-table #string #counting #sorting"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Name Translated: #数组 #哈希表 #字符串 #计数 #排序"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Solution Name: rankTeams"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Translated Title: #通过投票对团队排名"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Translated Content:\n",
    "<p>现在有一个特殊的排名系统，依据参赛团队在投票人心中的次序进行排名，每个投票者都需要按从高到低的顺序对参与排名的所有团队进行排位。</p>\n",
    "\n",
    "<p>排名规则如下：</p>\n",
    "\n",
    "<ul>\n",
    "\t<li>参赛团队的排名次序依照其所获「排位第一」的票的多少决定。如果存在多个团队并列的情况，将继续考虑其「排位第二」的票的数量。以此类推，直到不再存在并列的情况。</li>\n",
    "\t<li>如果在考虑完所有投票情况后仍然出现并列现象，则根据团队字母的字母顺序进行排名。</li>\n",
    "</ul>\n",
    "\n",
    "<p>给你一个字符串数组&nbsp;<code>votes</code> 代表全体投票者给出的排位情况，请你根据上述排名规则对所有参赛团队进行排名。</p>\n",
    "\n",
    "<p>请你返回能表示按排名系统 <strong>排序后</strong> 的所有团队排名的字符串。</p>\n",
    "\n",
    "<p>&nbsp;</p>\n",
    "\n",
    "<p><strong>示例 1：</strong></p>\n",
    "\n",
    "<pre><strong>输入：</strong>votes = [&quot;ABC&quot;,&quot;ACB&quot;,&quot;ABC&quot;,&quot;ACB&quot;,&quot;ACB&quot;]\n",
    "<strong>输出：</strong>&quot;ACB&quot;\n",
    "<strong>解释：</strong>A 队获得五票「排位第一」，没有其他队获得「排位第一」，所以 A 队排名第一。\n",
    "B 队获得两票「排位第二」，三票「排位第三」。\n",
    "C 队获得三票「排位第二」，两票「排位第三」。\n",
    "由于 C 队「排位第二」的票数较多，所以 C 队排第二，B 队排第三。\n",
    "</pre>\n",
    "\n",
    "<p><strong>示例 2：</strong></p>\n",
    "\n",
    "<pre><strong>输入：</strong>votes = [&quot;WXYZ&quot;,&quot;XYZW&quot;]\n",
    "<strong>输出：</strong>&quot;XWYZ&quot;\n",
    "<strong>解释：</strong>X 队在并列僵局打破后成为排名第一的团队。X 队和 W 队的「排位第一」票数一样，但是 X 队有一票「排位第二」，而 W 没有获得「排位第二」。 \n",
    "</pre>\n",
    "\n",
    "<p><strong>示例 3：</strong></p>\n",
    "\n",
    "<pre><strong>输入：</strong>votes = [&quot;ZMNAGUEDSJYLBOPHRQICWFXTVK&quot;]\n",
    "<strong>输出：</strong>&quot;ZMNAGUEDSJYLBOPHRQICWFXTVK&quot;\n",
    "<strong>解释：</strong>只有一个投票者，所以排名完全按照他的意愿。\n",
    "</pre>\n",
    "\n",
    "<p><strong>示例 4：</strong></p>\n",
    "\n",
    "<pre><strong>输入：</strong>votes = [&quot;BCA&quot;,&quot;CAB&quot;,&quot;CBA&quot;,&quot;ABC&quot;,&quot;ACB&quot;,&quot;BAC&quot;]\n",
    "<strong>输出：</strong>&quot;ABC&quot;\n",
    "<strong>解释：</strong> \n",
    "A 队获得两票「排位第一」，两票「排位第二」，两票「排位第三」。\n",
    "B 队获得两票「排位第一」，两票「排位第二」，两票「排位第三」。\n",
    "C 队获得两票「排位第一」，两票「排位第二」，两票「排位第三」。\n",
    "完全并列，所以我们需要按照字母升序排名。\n",
    "</pre>\n",
    "\n",
    "<p><strong>示例 5：</strong></p>\n",
    "\n",
    "<pre><strong>输入：</strong>votes = [&quot;M&quot;,&quot;M&quot;,&quot;M&quot;,&quot;M&quot;]\n",
    "<strong>输出：</strong>&quot;M&quot;\n",
    "<strong>解释：</strong>只有 M 队参赛，所以它排名第一。\n",
    "</pre>\n",
    "\n",
    "<p>&nbsp;</p>\n",
    "\n",
    "<p><strong>提示：</strong></p>\n",
    "\n",
    "<ul>\n",
    "\t<li><code>1 &lt;= votes.length &lt;= 1000</code></li>\n",
    "\t<li><code>1 &lt;= votes[i].length &lt;= 26</code></li>\n",
    "\t<li><code>votes[i].length ==&nbsp;votes[j].length</code> for&nbsp;<code>0 &lt;= i, j &lt; votes.length</code></li>\n",
    "\t<li><code>votes[i][j]</code>&nbsp;是英文 <strong>大写</strong> 字母</li>\n",
    "\t<li><code>votes[i]</code>&nbsp;中的所有字母都是唯一的</li>\n",
    "\t<li><code>votes[0]</code>&nbsp;中出现的所有字母 <strong>同样也</strong> 出现在&nbsp;<code>votes[j]</code>&nbsp;中，其中&nbsp;<code>1 &lt;= j &lt; votes.length</code></li>\n",
    "</ul>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Description: [rank-teams-by-votes](https://leetcode.cn/problems/rank-teams-by-votes/description/)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Solutions: [rank-teams-by-votes](https://leetcode.cn/problems/rank-teams-by-votes/solutions/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_cases = ['[\"ABC\",\"ACB\",\"ABC\",\"ACB\",\"ACB\"]', '[\"WXYZ\",\"XYZW\"]', '[\"ZMNAGUEDSJYLBOPHRQICWFXTVK\"]']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        count = {v: [0] * len(votes[0]) + [v] for v in votes[0]}\n",
    "\n",
    "        for vote in votes:\n",
    "            for i, v in enumerate(vote):\n",
    "                count[v][i] -= 1\n",
    "\n",
    "        return ''.join(sorted(votes[0], key=count.get))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "  def rankTeams(self, votes: List[str]) -> str:\n",
    "    b = ord('A')\n",
    "    r = [0] * 26\n",
    "    ret, q = [], []\n",
    "    l = len(votes[0])\n",
    "    for i in range(l):\n",
    "      for v in votes:\n",
    "        # print(f\"vote for {v[i]}\")\n",
    "        t = ord(v[i]) - b\n",
    "        r[t] = r[t] +  r[t] + 26 ** (l - i)\n",
    "      \n",
    "    for i in range(26):\n",
    "      if r[i] > 0:\n",
    "        heapq.heappush(q, (-r[i], chr(b + i)))\n",
    "    while len(q)>0:\n",
    "      s, v = heapq.heappop(q)\n",
    "      # print(f\"find score {s}\")\n",
    "      ret.append(v)\n",
    "    return \"\".join(ret)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        def compare(x, y):\n",
    "            for i in range(len(votes[0])):\n",
    "                count_x = 0\n",
    "                count_y = 0\n",
    "                for vote in votes:\n",
    "                    if vote[i] == x:\n",
    "                        count_x += 1\n",
    "                    if vote[i] == y:\n",
    "                        count_y += 1\n",
    "                if count_x != count_y:\n",
    "                    return 1 if count_x < count_y else -1\n",
    "            return 1 if x > y else -1\n",
    "        \n",
    "        teams = [i for i in votes[0]]\n",
    "        teams.sort(key=cmp_to_key(compare))\n",
    "        return \"\".join(teams)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        teams_num = len(votes[0])\n",
    "        rank_dic = defaultdict(lambda: [0] * teams_num)\n",
    "        rank_lst = list()\n",
    "        res = ''\n",
    "\n",
    "        # 只有一个投票者\n",
    "        if len(votes) == 1:\n",
    "            return votes[0]\n",
    "\n",
    "        # 统计每个队伍的排名次数\n",
    "        for vote in votes:\n",
    "            for i, vid in enumerate(vote):\n",
    "                rank_dic[vid][i] += 1\n",
    "        \n",
    "        # 剪枝：只有一个队则直接返回\n",
    "        if len(rank_dic) == 1:\n",
    "            return votes[0]\n",
    "        \n",
    "        rank_lst = list(rank_dic.items())            \n",
    "        rank_lst.sort(key=lambda x: (x[1], -ord(x[0])), reverse=True)\n",
    "        return \"\".join(vid for vid, rank in rank_lst)\n",
    "        \n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        if len(votes) == 1:\n",
    "            return votes[0]\n",
    "        elif len(votes[0]) == 1:\n",
    "            return votes[0]\n",
    "        else:\n",
    "            people_num = len(votes[0])\n",
    "            vote_num = len(votes)\n",
    "            my_dict = dict()\n",
    "            for vote_i in votes:\n",
    "                for j, people_j in enumerate(vote_i):\n",
    "                    if people_j not in my_dict:\n",
    "                        my_dict[people_j] = [0] * people_num\n",
    "                        my_dict[people_j][j] += 1\n",
    "                    else:\n",
    "                        my_dict[people_j][j] += 1\n",
    "            my_dict_list = []\n",
    "            for key, value in my_dict.items():\n",
    "                cur = [key] + value\n",
    "                my_dict_list.append(cur)\n",
    "\n",
    "            my_dict_list_new = sorted(my_dict_list, key=lambda x: tuple([-x[i] for i in range(1, people_num)] + [x[0]]))\n",
    "            result = \"\"\n",
    "            for item in my_dict_list_new:\n",
    "                result = result + item[0]\n",
    "            return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        team=list(set(list(votes[0])))\n",
    "        team.sort()\n",
    "        dic={}\n",
    "        for v in votes:\n",
    "            for i in range(len(v)):\n",
    "                dic[v[i]]=dic.get(v[i],[0 for _ in range(len(team))])\n",
    "                dic[v[i]][i]+=1\n",
    "        temp=[]\n",
    "        for k in dic.keys():\n",
    "            temp.append(dic[k]+[ord('Z')-ord(k)])\n",
    "        temp.sort(reverse=True)\n",
    "        res=''\n",
    "        for t in temp:\n",
    "            res+=chr(ord('Z')-t[-1])\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        if len(votes) == 1:\n",
    "            return votes[0]\n",
    "        \n",
    "        # 共多少位投票者\n",
    "        num_people = len(votes[0])\n",
    "        # 初始化字典\n",
    "        res_dict = {}\n",
    "        for key in votes[0]:\n",
    "            res_dict[key] = [0] * num_people\n",
    "        # 索引代表排位\n",
    "        for i in range(len(votes)):\n",
    "            for j in range(num_people):\n",
    "                if votes[i][j] in res_dict:\n",
    "                    res_dict[votes[i][j]][j] += 1\n",
    "                else:\n",
    "                    # print(res_dict)\n",
    "                    res_dict[votes[i][j]][j] = 1\n",
    "        \n",
    "        # res_list = []\n",
    "        # for key, value in res_dict.items():\n",
    "        #     res_list.append([key, max(value), value.index(max(value)) + 1])\n",
    "        \n",
    "        # 排序\n",
    "        idx = [i for i in range(len(res_dict[votes[0][0]]))]\n",
    "        \n",
    "        res_dict = sorted(res_dict.items(), key=lambda x: (x[1], -ord(x[0])), reverse=True)\n",
    "        # res_dict = sorted(res_dict.items(), key=lambda x: x[0])\n",
    "        # print(res_dict)\n",
    "        res = \"\"\n",
    "        for i in res_dict:\n",
    "            res += i[0]\n",
    "        return res\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        n = len(votes[0])\n",
    "        d = defaultdict(lambda:[0] * n)\n",
    "        for v in votes:\n",
    "            for i, t in enumerate(v):\n",
    "                d[t][i] -= 1\n",
    "        return ''.join(sorted(d, key=lambda k:(d[k], k)))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        n = len(votes[0])\n",
    "        d = {}\n",
    "        for ch in votes[0]:\n",
    "            d[ch] = [0] * n\n",
    "        \n",
    "        for vo in votes:\n",
    "            for i,ch in enumerate(vo) :\n",
    "                d[ch][i] += 1\n",
    "\n",
    "\n",
    "        ans = sorted(votes[0],key = lambda x:(d[x],-ord(x)) ,reverse = True)\n",
    "        return ''.join(ans)\n",
    "        \n",
    "\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        n = len(votes[0])\n",
    "        ranking = defaultdict(lambda: [0] * n)\n",
    "        for vote in votes:\n",
    "            for i, c in enumerate(vote):\n",
    "                ranking[c][i] += 1\n",
    "        result = list(ranking.items())\n",
    "        result.sort(key = lambda x: (x[1], -ord(x[0])), reverse = True)\n",
    "        return \"\".join(v for v, _ in result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        teams_num = len(votes[0])\n",
    "        rank_dic = defaultdict(lambda: [0] * teams_num)\n",
    "        rank_lst = list()\n",
    "\n",
    "        # 只有一个投票者\n",
    "        if len(votes) == 1:\n",
    "            return votes[0]\n",
    "\n",
    "        # 统计每个队伍的排名次数\n",
    "        for vote in votes:\n",
    "            for i, vid in enumerate(vote):\n",
    "                rank_dic[vid][i] += 1\n",
    "        \n",
    "        # 剪枝：只有一个队则直接返回\n",
    "        if len(rank_dic) == 1:\n",
    "            return votes[0]\n",
    "        \n",
    "        rank_lst = list(rank_dic.items())\n",
    "        rank_lst.sort(key=lambda x: (x[1], -ord(x[0])), reverse=True)\n",
    "        return \"\".join(vid for vid, rank in rank_lst)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        d = {i: [0]*len(votes[0]) for i in votes[0]}\n",
    "        for vote in votes:\n",
    "            for cnt, i in enumerate(vote): d[i][cnt]-=1\n",
    "        return ''.join(i[-1] for i in sorted([(*v, k) for k, v in d.items()]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        n = len(votes[0])\n",
    "        d = defaultdict(lambda: [0] * n)\n",
    "        for vote in votes:\n",
    "            for i, num in enumerate(vote):\n",
    "                d[num][i] -= 1\n",
    "        ans=list(d.items())\n",
    "        ans.sort(key=lambda x:(x[1],x[0]))\n",
    "        return ''.join(s[0] for s in ans)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        m = len(votes[0])\n",
    "        cnt = defaultdict(lambda: defaultdict(int))\n",
    "        for vote in votes:\n",
    "            for i in range(m):\n",
    "                cnt[vote[i]][i] += 1\n",
    "        ans = list(votes[0])\n",
    "        ans.sort(key=lambda x: [-cnt[x][i] for i in range(m)]+[x])\n",
    "        return \"\".join(ans)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        le = len(votes[0])\n",
    "        dic = {}\n",
    "        for item in votes[0]:\n",
    "            dic[item] = [0 for i in range(le)]\n",
    "        for i in range(le):\n",
    "            for vote in votes:\n",
    "                team = vote[i]\n",
    "                dic[team][i] += 1\n",
    "\n",
    "        result = list(dic.items())\n",
    "        result = sorted(result, key=lambda x: (x[1],-ord(x[0])), reverse = True)\n",
    "        return \"\".join([team for team,score in result])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        n, m = len(votes), len(votes[0])\n",
    "        letters = sorted(list(votes[0]))\n",
    "        c2i = {c: i for i, c in enumerate(letters)}\n",
    "        i2c = {i: c for i, c in enumerate(letters)}\n",
    "        result = [[0] * m for _ in range(m)]  # result[i][j] 表示第i个字母出现名次j的次数\n",
    "        for vote in votes:\n",
    "            for i, x in enumerate(vote):\n",
    "                result[c2i[x]][i] += 1\n",
    "        ans = []\n",
    "        for i, x in sorted(enumerate(result), key=lambda x:[x[1], -x[0]], reverse=True):\n",
    "            ans.append(i2c[i])\n",
    "        return ''.join(ans)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        d = collections.defaultdict(lambda:[0]*len(votes[0]))\n",
    "        for vote in votes:\n",
    "            for i,v in enumerate(vote):\n",
    "                d[v][i] -= 1\n",
    "        res = sorted(votes[0],key=lambda x:(d[x],x))\n",
    "        return ''.join(res)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "import functools\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        votes_map = {}\n",
    "        for vote in votes:\n",
    "            for i in range(len(vote)):\n",
    "                if vote[i] not in votes_map.keys():\n",
    "                    votes_map[vote[i]] = [0]*len(vote)+[vote[i]]\n",
    "                votes_map[vote[i]][i] += 1\n",
    "        rank = []\n",
    "        for value in votes_map.values():\n",
    "            rank.append(value)\n",
    "        def sort_item(item1, item2):\n",
    "            for i in range(len(item1)-1):\n",
    "                if item1[i] != item2[i]:\n",
    "                    return item2[i] - item1[i]\n",
    "            return ord(item1[-1])-ord(item2[-1])\n",
    "        rank.sort(key=functools.cmp_to_key(sort_item))\n",
    "        result = \"\"\n",
    "        for res in rank:\n",
    "            result += res[-1]\n",
    "        return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        d = defaultdict(lambda:[0] * 26)\n",
    "        for v in votes:\n",
    "            for i, t in enumerate(v):\n",
    "                d[t][i] -= 1\n",
    "        return ''.join(sorted(d, key=lambda k:(d[k], k)))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        n = len(votes[0])\n",
    "        dic = defaultdict(lambda: [0] * n)\n",
    "        for vote in votes:\n",
    "            for i, v in enumerate(vote):\n",
    "                dic[v][i] += 1\n",
    "        result = list(dic.items())\n",
    "        result.sort(key=lambda x: (x[1], -ord(x[0])), reverse=True)\n",
    "        return \"\".join([v for v, value in result])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        n = len(votes[0])\n",
    "        ranking = defaultdict(lambda: [0] * n)\n",
    "        for vote in votes:\n",
    "            for i, vid in enumerate(vote):\n",
    "                ranking[vid][i] += 1\n",
    "\n",
    "        result = list(ranking.items())\n",
    "        result.sort(key = lambda x: (x[1], -ord(x[0])), reverse = True)\n",
    "        return ''.join([vid for vid, rank in result])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        n = len(votes)\n",
    "        group_rank = {}\n",
    "        group_cnt = len(votes[0])\n",
    "        for c in votes[0]:\n",
    "            group_rank[c] = [0]*group_cnt\n",
    "        for vote in votes:\n",
    "            for i in range(group_cnt):\n",
    "                group_rank[vote[i]][i] += 1\n",
    "        group_rank = [group_rank[k]+[k] for k in group_rank] \n",
    "        group_rank.sort(key=lambda x:([-x[i] for i in range(group_cnt)] + [x[-1]]))\n",
    "        return ''.join([g[-1] for g in group_rank])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        chs, leng = list(votes[0]), len(votes[0])\n",
    "    \n",
    "        d = {ch : [0] * (leng + 1) for ch in chs}\n",
    "        for ch in d:\n",
    "            d[ch][-1] = -ord(ch)\n",
    "        \n",
    "        for vote in votes:\n",
    "            for i, ch in enumerate(vote):\n",
    "                d[ch][i] += 1\n",
    "        \n",
    "        ans = sorted(chs, key=lambda ch: d[ch], reverse= True)\n",
    "    \n",
    "        return \"\".join(ans)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        d = defaultdict(lambda:[1000] * len(votes[0]))\n",
    "        for v in votes:\n",
    "            for i, t in enumerate(v):\n",
    "                d[t][i] -= 1\n",
    "        return ''.join(sorted(d, key=lambda k:(d[k], k)))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        rankStats = {}\n",
    "        voteLen = len(votes[0])\n",
    "\n",
    "        for vote in votes:\n",
    "            for rank, team in enumerate(vote):\n",
    "                if team not in rankStats:\n",
    "                    rankStats[team] = [0] * voteLen\n",
    "                rankStats[team][rank] -= 1\n",
    "\n",
    "        teams = []\n",
    "        for team, rank in rankStats.items():\n",
    "            teams.append([team, rank])\n",
    "        teams.sort(key = lambda x: (x[1], ord(x[0])))\n",
    "\n",
    "        results = []\n",
    "        for team, rank in teams:\n",
    "            results.append(team)\n",
    "        return ''.join(results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        n = len(votes[0])\n",
    "        d = {}\n",
    "        for ch in votes[0]:\n",
    "            d[ch] = [0] * n\n",
    "        \n",
    "        for vo in votes:\n",
    "            for i,ch in enumerate(vo) :\n",
    "                d[ch][i] += 1\n",
    "\n",
    "        s = list(votes[0])\n",
    "\n",
    "        # ans = sorted(votes[0],key = lambda x:(d[x],-ord(x)) ,reverse = True)\n",
    "        s.sort(reverse = True,key = lambda x:(d[x],-ord(x)))\n",
    "\n",
    "        return ''.join(s)\n",
    "        \n",
    "\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        d = defaultdict(lambda:[0] * 26)\n",
    "        for v in votes:\n",
    "            for i, t in enumerate(v):\n",
    "                d[t][i] -= 1\n",
    "        return ''.join(sorted(d, key=lambda k:(d[k], k)))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: list[str]) -> str:\n",
    "        n = len(votes[0])\n",
    "        rank = defaultdict(lambda: [0] * n)\n",
    "        for vote in votes:\n",
    "            for index, t in enumerate(vote):\n",
    "                rank[t][index] -= 1\n",
    "\n",
    "        ans = list(rank.items())\n",
    "        ans.sort(key=lambda x: (x[1], ord(x[0])))\n",
    "        return ''.join([r[0] for r in ans])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        d = defaultdict(lambda:[0] * 26)\n",
    "        for v in votes:\n",
    "            for i, t in enumerate(v):\n",
    "                d[t][i] -= 1\n",
    "        return ''.join(sorted(d, key=lambda k:(d[k], k)))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "from collections import defaultdict\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        n = len(votes[0])\n",
    "        keys = list(votes[0])\n",
    "        counters = dict()\n",
    "        for k in keys:\n",
    "            counters[k] = [0] * n + [k]\n",
    "        for vote in votes:\n",
    "            for i, k in enumerate(vote):\n",
    "                counters[k][i] -= 1\n",
    "        values = list(counters.values())\n",
    "        values.sort()\n",
    "        result = list()\n",
    "        for v in values:\n",
    "            result.append(v[-1])\n",
    "        return \"\".join(result)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        n = len(votes[0])\n",
    "        rank = defaultdict(lambda: [0]*n)\n",
    "        for vote in votes:\n",
    "            for i,team in enumerate(vote):\n",
    "                rank[team][i] += 1\n",
    "        result = list(rank.items())\n",
    "        result.sort(key=lambda x:(x[1],-ord(x[0])),reverse = True)\n",
    "        return ''.join(x[0] for x in result)\n",
    "            \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        \n",
    "        n = len(votes[0])\n",
    "        letters = defaultdict(lambda:[0] * n)\n",
    "        for vo in votes:\n",
    "            for i, ch in enumerate(vo):\n",
    "                letters[ch][i] += 1\n",
    "\n",
    "        res = \"\"\n",
    "        sorted_letters = sorted(letters.items(), key = lambda x: (x[1], -ord(x[0])))\n",
    "        # print(sorted_letters)\n",
    "        for i in range(len(sorted_letters) - 1, -1, -1):\n",
    "            res += sorted_letters[i][0]\n",
    "        return res\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        d = defaultdict(lambda:[0] * len(votes[0]))\n",
    "        for v in votes:\n",
    "            for i, t in enumerate(v):\n",
    "                d[t][i] -= 1\n",
    "        return ''.join(sorted(d, key=lambda k:(d[k], k)))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        n = len(votes[0])\n",
    "        ranking = collections.defaultdict(lambda: [0]*n)\n",
    "        for vote in votes:\n",
    "            for i, vid in enumerate(vote):\n",
    "                ranking[vid][i] += 1\n",
    "        \n",
    "        result = list(ranking.items())\n",
    "        result.sort(key= lambda x: (x[1], -ord(x[0])), reverse = True)\n",
    "        return \"\".join([vid for vid, rank in result])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        n = len(votes[0])\n",
    "        # 初始化哈希映射\n",
    "        # 这个初始化的方式很巧妙， 初始化一个map里面有[0] * n个数\n",
    "        ranking = collections.defaultdict(lambda: [0] * n)\n",
    "        # 遍历统计\n",
    "        for vote in votes:\n",
    "            for i, vid in enumerate(vote):\n",
    "                ranking[vid][i] += 1\n",
    "        \n",
    "        # 取出所有的键值对，记住这个取出键值对的方法\n",
    "        result = list(ranking.items())\n",
    "        # 排序，多个序列排序\n",
    "        result.sort(key=lambda x: (x[1], -ord(x[0])), reverse=True)\n",
    "        # 最后 将map中的key 转化为str，这个方法最好也记住\n",
    "        return \"\".join([vid for vid, rank in result])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        positions = len(votes[0])\n",
    "        memo = defaultdict(lambda: [0] * positions)  # team_id -> [votes for position 1, votes for position 2, ...]\n",
    "        for vote in votes:\n",
    "            for i, team_id in enumerate(vote):\n",
    "                memo[team_id][i] -= 1\n",
    "        arr = sorted(ranks + [team_id] for team_id, ranks in memo.items())\n",
    "        return ''.join(item[-1] for item in arr)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes) -> str:\n",
    "        if len(votes)==1 or len(votes[0])==1:\n",
    "            return votes[0]\n",
    "        score = defaultdict(lambda:[0]*len(votes[0]))\n",
    "\n",
    "        for v in votes:\n",
    "            for i in range(len(v)):\n",
    "                score[v[i]][i] -= 1\n",
    "        \n",
    "        ans=sorted(votes[0],key=lambda x:(score[x],x))\n",
    "\n",
    "        return \"\".join(ans)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        n = len(votes[0])\n",
    "        cnt = defaultdict(lambda :[0 for _ in range(n)])\n",
    "        for s in votes:\n",
    "            for i in range(n):\n",
    "                cnt[s[i]][i] += 1\n",
    "        ranks = [cnt[v] + [ord(v) - ord('A')] for v in cnt]\n",
    "      \n",
    "        ranks.sort(key = lambda x:(x[:-1],-x[-1]))\n",
    "        return ''.join([chr(ord('A') + v[-1]) for v in ranks[::-1]])\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        n = len(votes[0])\n",
    "        # 初始化哈希映射\n",
    "        ranking = collections.defaultdict(lambda: [0] * n)\n",
    "        # 遍历统计\n",
    "        for vote in votes:\n",
    "            for i, vid in enumerate(vote):\n",
    "                ranking[vid][i] += 1\n",
    "        \n",
    "        # 取出所有的键值对\n",
    "        result = list(ranking.items())\n",
    "        # 排序\n",
    "        result.sort(key=lambda x: (x[1], -ord(x[0])), reverse=True)\n",
    "        return \"\".join([vid for vid, rank in result])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        ranks_map = {}\n",
    "        ranks = []\n",
    "        result = \"\"\n",
    "        for vote in votes:\n",
    "            for i in range(len(vote)):\n",
    "                if vote[i] not in ranks_map.keys():\n",
    "                    ranks_map[vote[i]] = [0]*len(vote) + [vote[i]]\n",
    "                ranks_map[vote[i]][i] += 1\n",
    "        for rank in ranks_map.values():\n",
    "            ranks.append(rank)\n",
    "        def rank_sort(item1, item2):\n",
    "            for i in range(len(item1)-1):\n",
    "                if item1[i] != item2[i]:\n",
    "                    return item2[i] - item1[i]\n",
    "            return ord(item1[-1]) - ord(item2[-1])\n",
    "        ranks.sort(key = functools.cmp_to_key(rank_sort))\n",
    "        for rank in ranks:\n",
    "            result += rank[-1]\n",
    "        return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        m = len(votes)\n",
    "        n = len(votes[0])\n",
    "        team = defaultdict(list)\n",
    "        for c in votes[0] :\n",
    "            team[c] = [0] * n\n",
    "    \n",
    "        for v in votes :\n",
    "            for i in range(len(v)) :\n",
    "                team[v[i]][i] += 1\n",
    "        arr = []\n",
    "        for k, v in team.items() :\n",
    "            arr.append(tuple(v+[-ord(k)]))\n",
    "        arr.sort(reverse = True)\n",
    "\n",
    "        return ''.join([chr(-a[-1]) for a in arr])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        keys = votes[0]\n",
    "        dic = {i: [0] * len(keys) for i in keys}\n",
    "\n",
    "        for each in votes:\n",
    "            for i, value in enumerate(each):\n",
    "                dic[value][i] += 1\n",
    "\n",
    "        # 根据键值对排序\n",
    "        res = sorted(dic.items(), key=lambda x: (x[1], -ord(x[0])), reverse=True)\n",
    "        print(res)\n",
    "        ans = ''\n",
    "        for i in res:\n",
    "            ans += i[0]\n",
    "\n",
    "        return ans "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        d = defaultdict(lambda:[0] * len(votes[0]))\n",
    "        for v in votes:\n",
    "            for i, t in enumerate(v):\n",
    "                d[t][i] -= 1\n",
    "        return ''.join(sorted(d, key=lambda k:(d[k], k)))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        teamNum = len(votes[0])\n",
    "        teamDic = {}\n",
    "        tStr = votes[0]\n",
    "        for team in tStr:\n",
    "            teamDic[team] = [0 for _ in range(teamNum)]\n",
    "        for tStr in votes:\n",
    "            i = 0\n",
    "            for team in tStr:\n",
    "                teamDic[team][i] += 1\n",
    "                i += 1\n",
    "        result = list(teamDic.items())\n",
    "        result.sort(key=lambda x: (x[1], -ord(x[0])), reverse=True)\n",
    "        return \"\".join([vid for vid, rank in result])\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        score = defaultdict(lambda : [0]*len(votes[0]))\n",
    "        for v in votes:\n",
    "            for i, c in enumerate(v):\n",
    "                score[c][i] -= 1\n",
    "        return \"\".join(sorted(score.keys(), key=lambda x: (score[x], x)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        n = len(votes[0])\n",
    "        # 初始化哈希映射\n",
    "        ranking = collections.defaultdict(lambda: [0] * n)\n",
    "        # 遍历统计\n",
    "        for vote in votes:\n",
    "            for i, c in enumerate(vote):\n",
    "                ranking[c][i] += 1\n",
    "\n",
    "        # 取出所有的键值对\n",
    "        result = list(ranking.items())\n",
    "        # 排序\n",
    "        result.sort(key=lambda x: (x[1], -ord(x[0])), reverse=True)\n",
    "        return \"\".join([c for c, _ in result])\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        n = len(votes[0])\n",
    "        # 初始化哈希映射\n",
    "        ranking = collections.defaultdict(lambda: [0] * n)\n",
    "        # 遍历统计\n",
    "        for vote in votes:\n",
    "            for i, vid in enumerate(vote):\n",
    "                ranking[vid][i] += 1\n",
    "        \n",
    "        # 取出所有的键值对\n",
    "        result = list(ranking.items())\n",
    "        # 排序\n",
    "        result.sort(key=lambda x: (x[1], -ord(x[0])), reverse=True)\n",
    "        return \"\".join([vid for vid, rank in result])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        n = len(votes[0])\n",
    "        # 初始化哈希映射\n",
    "        ranking = collections.defaultdict(lambda: [0] * n)\n",
    "        # 遍历统计\n",
    "        for vote in votes:\n",
    "            for i, vid in enumerate(vote):\n",
    "                ranking[vid][i] += 1\n",
    "        \n",
    "        # 取出所有的键值对\n",
    "        result = list(ranking.items())\n",
    "        # 排序\n",
    "        result.sort(key=lambda x: (x[1], -ord(x[0])), reverse=True)\n",
    "        return \"\".join([vid for vid, rank in result])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        n = len(votes[0])\n",
    "\n",
    "        ranking = collections.defaultdict(lambda: [0] * n)\n",
    "\n",
    "        for vote in votes:\n",
    "            for i, v in enumerate(vote):\n",
    "                ranking[v][i] += 1\n",
    "        \n",
    "        result = list(ranking.items())\n",
    "        result.sort(key = lambda x : (x[1], -ord(x[0])), reverse = True)\n",
    "        print(result)\n",
    "        return \"\".join([v for v, rank in result])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        mm = {}\n",
    "        for i in range(len(votes)):\n",
    "            s = votes[i]\n",
    "            for j in range(len(s)):\n",
    "                cur_ch = s[j]\n",
    "                if cur_ch in mm:\n",
    "                    mm[cur_ch][j] = mm[cur_ch][j] + 1\n",
    "                else:\n",
    "                    mm[cur_ch] = [0] * len(votes[0])\n",
    "                    mm[cur_ch][j] = mm[cur_ch][j] + 1\n",
    "\n",
    "        # 使用python map sort方法， 从小到大排序，小的是排行在最后面的，对应字母刚好是反着的\n",
    "        mm = sorted(mm.items(), key = lambda x: (x[1], -ord(x[0])))\n",
    "\n",
    "        res = \"\"\n",
    "        for key, value in mm:\n",
    "            res = key + res\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def dfs(self, cands, pos):\n",
    "        if pos == self.length:\n",
    "            arr = list(cands)\n",
    "            arr.sort()\n",
    "            return ''.join(arr)\n",
    "        \n",
    "        cnts = dict()\n",
    "        for c in cands:\n",
    "            cnts[c] = 0\n",
    "        \n",
    "        for i in range(len(self.votes)):\n",
    "            if self.votes[i][pos] in cnts:\n",
    "                cnts[self.votes[i][pos]] += 1\n",
    "        \n",
    "        arr = []\n",
    "        for k, v in cnts.items():\n",
    "            arr.append((v, k))\n",
    "        \n",
    "        arr.sort(key=lambda x:(-x[0], x[1]))\n",
    "        i = 0\n",
    "        res = \"\"\n",
    "        while i < len(arr):\n",
    "            if i < len(arr) - 1 and arr[i][0] > arr[i+1][0]:\n",
    "                res += arr[i][1]\n",
    "                i += 1\n",
    "            else:\n",
    "                tmp = set()\n",
    "                j = i\n",
    "                while j < len(arr) and arr[j][0] == arr[i][0]:\n",
    "                    tmp.add(arr[j][1])\n",
    "                    j += 1\n",
    "                res += self.dfs(tmp, pos+1)\n",
    "                i = j\n",
    "        \n",
    "        return res\n",
    "\n",
    "\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        self.votes = votes\n",
    "        self.length = len(votes[0])\n",
    "\n",
    "        st = set()\n",
    "        for c in votes[0]:\n",
    "            st.add(c)\n",
    "\n",
    "        return self.dfs(st, 0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        n = len(votes[0])\n",
    "        ranking = defaultdict(lambda: [0] * n)\n",
    "        for vote in votes:\n",
    "            for rank, team in enumerate(vote):\n",
    "                ranking[team][rank] -= 1\n",
    "        \n",
    "        ans = sorted(votes[0], key=lambda x: (ranking[x], x))\n",
    "        return ''.join(ans)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        n = len(votes[0])\n",
    "        rank = defaultdict(lambda: [0]*n)\n",
    "        for vote in votes:\n",
    "            for i,team in enumerate(vote):\n",
    "                rank[team][i] += 1\n",
    "        result = list(rank.items())\n",
    "        result.sort(key=lambda x:(x[1],-ord(x[0])),reverse = True)\n",
    "        return ''.join(x[0] for x in result)\n",
    "            \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        n = len(votes[0])\n",
    "        # 初始化哈希映射\n",
    "        ranking = collections.defaultdict(lambda: [0] * n)\n",
    "        # 遍历统计\n",
    "        for vote in votes:\n",
    "            for i, c in enumerate(vote):\n",
    "                ranking[c][i] += 1\n",
    "\n",
    "        # 取出所有的键值对\n",
    "        result = list(ranking.items())\n",
    "        # 排序\n",
    "        result.sort(key=lambda x: (x[1], -ord(x[0])), reverse=True)\n",
    "        return \"\".join([vid for vid, rank in result])\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        n = len(votes[0])\n",
    "        # 初始化哈希映射\n",
    "        ranking = collections.defaultdict(lambda: [0] * n)\n",
    "        # 遍历统计\n",
    "        for vote in votes:\n",
    "            for i, vid in enumerate(vote):\n",
    "                ranking[vid][i] += 1\n",
    "        \n",
    "        # 取出所有的键值对\n",
    "        result = list(ranking.items())\n",
    "        # 排序\n",
    "        result.sort(key=lambda x: (x[1], -ord(x[0])), reverse=True)\n",
    "        return \"\".join([vid for vid, rank in result])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        n = len(votes[0])\n",
    "        # 初始化哈希映射\n",
    "        ranking = collections.defaultdict(lambda: [0] * n)\n",
    "        # 遍历统计\n",
    "        for vote in votes:\n",
    "            for i, vid in enumerate(vote):\n",
    "                ranking[vid][i] += 1\n",
    "        \n",
    "        # 取出所有的键值对\n",
    "        result = list(ranking.items())\n",
    "        # 排序\n",
    "        result.sort(key=lambda x: (x[1], -ord(x[0])), reverse=True)\n",
    "        return \"\".join([vid for vid, rank in result])\n",
    " "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        n = len(votes[0])\n",
    "\n",
    "        ranking = collections.defaultdict(lambda: [0] * n)\n",
    "\n",
    "        for vote in votes:\n",
    "            for i, v in enumerate(vote):\n",
    "                ranking[v][i] += 1\n",
    "        \n",
    "        result = list(ranking.items())\n",
    "        result.sort(key = lambda x : (x[1], -ord(x[0])), reverse = True)\n",
    "        print(result)\n",
    "        return \"\".join([v for v, rank in result])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        if len(votes) == 1:\n",
    "            return votes[0]\n",
    "        d = {}\n",
    "        for i in votes[0]:\n",
    "            d[i] = []        \n",
    "        \n",
    "        for vote in votes:\n",
    "            for char in range(len(votes[0])):\n",
    "                d[vote[char]].append(vote.index(vote[char]))\n",
    "        new_d = {}\n",
    "        for key, value in d.items():\n",
    "            new_d[key] = []\n",
    "            for i in range(len(votes[0])):\n",
    "                new_d[key].append(value.count(i))\n",
    "        \n",
    "        result = list(new_d.items())\n",
    "        result.sort(key = lambda x: (x[1], -ord(x[0])), reverse = True)\n",
    "        return ''.join(v[0] for v in result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        if len(votes) == 1:\n",
    "            return votes[0]\n",
    "        d = {}\n",
    "        for i in votes[0]:\n",
    "            d[i] = []        \n",
    "        \n",
    "        for vote in votes:\n",
    "            for char in range(len(votes[0])):\n",
    "                d[vote[char]].append(vote.index(vote[char]))\n",
    "        new_d = {}\n",
    "        for key, value in d.items():\n",
    "            new_d[key] = []\n",
    "            for i in range(len(votes[0])):\n",
    "                new_d[key].append(value.count(i))\n",
    "        \n",
    "        result = list(new_d.items())\n",
    "        result.sort(key = lambda x: (x[1], -ord(x[0])), reverse = True)\n",
    "        return ''.join(v[0] for v in result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        words = dict()\n",
    "        for vote in votes:\n",
    "            for i in range(len(vote)):\n",
    "                if vote[i] in words:\n",
    "                    words[vote[i]].append(i)\n",
    "                    words[vote[i]].sort()\n",
    "                else:\n",
    "                    words[vote[i]] = [i]\n",
    "        words = {key:words[key] for key in sorted(words.keys())}\n",
    "        words = sorted(words, key = lambda key:words[key])\n",
    "        return \"\".join(words)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        rank = [[] for _ in range(26)]\n",
    "        for vote in votes:\n",
    "            for idx,ch in enumerate(vote):\n",
    "                rank[ord(ch)-ord('A')].append(idx+1)\n",
    "\n",
    "        for i in range(26):\n",
    "            rank[i].sort()\n",
    "\n",
    "        for i in range(len(rank)):\n",
    "            rank[i].append(i)\n",
    "        \n",
    "        rank.sort()\n",
    "        res = []\n",
    "        for r in rank:\n",
    "            if len(r)>1:\n",
    "                res.append(chr(r[-1]+ord('A')))\n",
    "        return \"\".join(res)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def rankTeams(self, votes: List[str]) -> str:\n",
    "        words=dict()\n",
    "        for vote in votes:\n",
    "            for i in range(len(vote)):\n",
    "                if vote[i] in words:\n",
    "                    words[vote[i]].append(i)\n",
    "                    words[vote[i]].sort()\n",
    "                else:\n",
    "                    words[vote[i]]=[i]\n",
    "        words={key:words[key] for key in sorted(words.keys())}\n",
    "        words=sorted(words,key=lambda key:words[key])\n",
    "        return \"\".join(words)\n"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 2
}
